package com.moto.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.moto.entity.Address;
import com.moto.entity.Car;
import com.moto.entityDto.AddressUpdateDto;
import com.moto.interceptor.BaseContext;
import com.moto.result.Result;
import com.moto.service.IAddressService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hyf
 * @since 2023-09-04
 */
@RestController
@RequestMapping("/moto/address")
@Api(tags = "收货地址接口")
@Slf4j
@CrossOrigin("*")
public class AddressController {
    @Autowired
    private IAddressService addressService;

    /**
     * 新增地址
     */
    @PostMapping("/addAddress")
    @ApiOperation("新增地址")
    public Result<Address> addAddress(@RequestBody Address address){
        log.info("新增地址:{}"+address);
        Integer id = Math.toIntExact(BaseContext.getCurrentId());
        address.setUId(id);
        addressService.addAddress(address);
        return Result.success();
    }

    /**
     * 删除地址
     */
    @DeleteMapping("/deleteAddress/{id}")
    @ApiOperation("删除地址")
    public Result deleteAddress(@PathVariable int id){
        log.info("删除地址：{}");
        addressService.removeById(id);
        return Result.success();
    }

    /**
     * 修改地址
     */
    @PostMapping("/updateAddressById")
    @ApiOperation("修改地址")
    public Result<Address> updateAddressById(@RequestBody AddressUpdateDto addressUpdateDto){
        log.info("修改地址");
        int id = Math.toIntExact(BaseContext.getCurrentId());
        addressService.updateIsDefault(id);
        addressService.updateAddressById(addressUpdateDto);
        return Result.success();
    }

    /**
     * 查询地址
     */
    @GetMapping("/selectAddress")
    @ApiOperation("查询地址")
    public Result<List<Address>> selectAddress(){
        log.info("查询地址");
        int id = Math.toIntExact(BaseContext.getCurrentId());
        LambdaQueryWrapper<Address> lqw = new LambdaQueryWrapper<Address>();
        lqw.eq(Address::getUId,id);
        List<Address> list = addressService.list(lqw);
        return Result.success(list);
    }
    /**
     * 回显地址
     */
    @GetMapping("/selectAddressById/{id}")
    @ApiOperation("回显地址")
    public Result<Address> selectAddress(@PathVariable int id){
        log.info("回显地址：{}",id);
        LambdaQueryWrapper<Address> lqw = new LambdaQueryWrapper<Address>();
        lqw.eq(Address::getAddressId,id);
        Address address = addressService.getOne(lqw);
        return Result.success(address);
    }


}
